import React from 'react';
import { Layout, Tooltip, Typography, Tag, Spin, message } from 'antd';
import marked from 'marked';
import hljs from 'highlight.js';
import moment from 'moment';
import { CalendarOutlined, CarryOutOutlined } from '@ant-design/icons/lib';

const { Content } = Layout;
const { Title } = Typography;


// todo: markdown https://segmentfault.com/a/1190000020294373
//                https://www.jianshu.com/p/fc4039505df4

export default class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      articleDetail: null,
      spinning: true,
    };
  }

  formatTime(time) {
    return moment(parseInt(new Date(time).getTime())).format('YYYY-MM-DD HH:mm');
  }

  _getArticle(id) {
    window.$http.get('/api/v1/article/query?id=' + id).then((res) => {
      this.setState({ articleDetail: res, spinning: false });
    }).catch((reason => {
      console.log('reason', reason.message);
      message.error('服务异常');
      this.setState({ spinning: false });
    }));
  }

  componentDidMount() {
    this._getArticle(this.props.history.location.query?.id);
    // 显示详情信息（包括tag）
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.setState({ articleDetail: this.state.articles[this.props.history.location.query?.id] });
  }

  componentWillMount() {
    hljs.initHighlightingOnLoad();
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: true,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: false,
      highlight: function(code) {
        return hljs.highlightAuto(code).value;
      },
    });

  }


  render() {
    return (
      <Content className="site-layout" style={{
        display: 'flex',
        flexDirection: 'column',
        margin: '10px auto', paddingTop: 5,
        // minHeight: 600,
        minWidth: 700, maxWidth: 900,
      }}>
        <Spin size={'large'} spinning={this.state.spinning}>
          <div className="site-layout-background"
               style={{ padding: '30px 80px', minHeight: 300, backgroundColor: '#f6f6f6' }}>
            <Title style={{ fontSize: 28 }}>{this.state?.articleDetail?.title}</Title>
            <div style={{ marginBottom: 10 }}>
              {
                this.state?.articleDetail ? <Tooltip placement="topRight" title="创建时间">
                <span style={{ cursor: 'help' }}>
                  <CalendarOutlined/>{this.formatTime(this.state?.articleDetail?.created_at)}
                </span></Tooltip> : null
              }

              {
                this.state?.articleDetail ? <Tooltip placement="topRight" title="修改时间">
                <span style={{ margin: '0 10px', cursor: 'help' }}>
                  <CarryOutOutlined/>{this.formatTime(this.state?.articleDetail?.updated_at)}
                </span></Tooltip> : null
              }


              {this.state?.articleDetail?.tags?.map((item) => {
                // console.log('item:', item);
                return <Tag key={item.id} color="default">{item?.tag.name}</Tag>;
              })}

            </div>
            <div id={'content'}
                 style={{
                   textAlign: 'left',
                   marginTop: 10,
                   flex: 1,
                   backgroundColor: '#f1f1f1',
                   padding: 20,
                   borderRadius: 10,
                 }}
                 dangerouslySetInnerHTML={{
                   __html: this.state?.articleDetail?.content ? marked(this.state.articleDetail.content) : null,
                 }}>
            </div>
          </div>
        </Spin>
      </Content>
    );
  }
}

